# -*- coding:utf-8 -*-

import requests
import re
import datetime as dt
from multiprocessing.dummy import Pool as ThreadPool
from selenium.common import exceptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from co_work.common import pre_config
from co_work.common.smtp_client_plain_html import send_mail
from co_work.common.ciyun import ciyun


class Search_Test_Record():

    def __init__(self, url, table_path, by_tester=False):

        self.table_path = table_path
        self.url = url
        self.driver = pre_config.chrome_brower(headless=True, proxy=False, download_path=self.table_path)
        self.by_tester = by_tester
        self.tester_set = set()

    def login(self):
        try:
            pre_config.open_page(self)
            WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "id_username")))
            pre_config.login_rdnet(self)
            WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.ID, "rep-report-title")))
            print "login pass!"
            return True
        except exceptions.TimeoutException:
            print "couldn't login, please try again..."
            return False

    def get_log_url(self):
        driver = self.driver
        try:
            condition = '//*[contains(@id,"-0-uiGrid-000C-cell")]'
            WebDriverWait(self.driver, 300).until(EC.presence_of_element_located((By.XPATH, condition)))
            if self.driver.find_element_by_xpath(condition).text != "":
                log_html_lists = driver.find_elements_by_xpath('//*[@ng-show="row.entity.hyperlink_set.test_logs_url"]')
                owner_log = driver.find_elements_by_css_selector('div.ui-grid-cell-contents.ng-binding.ng-scope')
                #owner_log = driver.find_elements_by_xpath('//*[@class="ui-grid-cell-contents ng-binding ng-scope"]')

                for fid, owner, log_html in zip(owner_log[1::6], owner_log[2::6], log_html_lists):
                    yield fid.get_attribute('title'), owner.get_attribute('title'), log_html.get_attribute('href')

        except exceptions.TimeoutException:
            print "couldn't find out the filter, Please try again......"

    def error_message(self, args):
        log_fid, log_tester, log_html = args
        # print log_html
        story_flag = False
        log_content = requests.get(log_html+'log.txt').content.split('\n')

        error_info = ""
        log_url = ""
        script_name_html = ""

        for line in log_content:

            if "http://logs.ute.nsn-rdnet.net/" in line:
                url = re.search(r'http://.*?html', line)
                log_url = '<td class="xl69" width="100" style="text-align: center">' \
                          '<a href="{0}" target="_parent">log url</a></td>'.format(url.group(0))

            elif '| FAIL |' in line:
                story_flag = True
                error_info += '<strong><font color="red">%s</font></strong><br>' % line

            elif story_flag and ("EGATE" in line or '======' in line or '------' in line):
                story_flag = False

            elif "testsuite/WMP" in line and script_name_html == "":
                script_name = re.search(r'^testsuite/WMP/(.*?)\.robot', line)
                script_name_html = '<tr height="19" style="height:15.0pt">\n' \
                                   '<td colspan="5" height="30" class="xl68" style="WORD-WRAP: break-word; background:RoyalBlue; color:white">' \
                                   '<strong>{0}</strong></td>\n' \
                                   '</tr>\n'.format(script_name.group(0))

            elif story_flag:
                error_info += line + "<br>"

        owner_fid_tr = '<tr height="20" style="height:15.0pt">\n' \
                       '<td height="20" class="xl70" width="85" style="height:15.0pt; background:gray; color:white">Owner</td>\n' \
                       '<td class="xl69" width="330" style="text-align: center">{0}</td>\n' \
                       '<td class="xl70" width="80" style="border-left:none; background:gray; color:white">Feature</td>\n' \
                       '<td class="xl69" width="330" style="text-align: center">{1}</td>\n' \
                       '{2}\n' \
                       '</tr>\n'.format(log_tester, log_fid, log_url)

        error_info_tr = '<tr height="86" style="mso-height-source:userset;height:64.5pt">\n' \
                        '<td colspan="5" height="86" class="xl65" style="WORD-WRAP: break-word">{0}</td>\n' \
                        '</tr>\n'.format(error_info)
        error_case_log = '<tbody>{0}\n{1}\n{2}\n</tbody>\n'.format(script_name_html, owner_fid_tr, error_info_tr)

        if self.by_tester:
            self.tester_set.add(log_tester)
            log_tester_file = self.table_path+'_'+log_tester
            with open(log_tester_file, 'a') as f_tester:
                f_tester.write(error_case_log)

        with open(self.table_path, 'a') as f_all:
            f_all.write(error_case_log)

    @staticmethod
    def write_page(file_path, name="all"):
        with open(file_path, 'r') as f:
            table_info = f.read()
            gen_html = '<html>' \
                       '<head></head>' \
                       '<body><p>Hi {0} :<br><br>' \
                       'Not Analysis Test Cases to be completed, please take actions!!<br><center><br>' \
                       '<p><img src="cid:image1"></p><br>'\
                       '<table border="2" style="TABLE-LAYOUT: fixed" border="1" cellspacing="0" cellpadding="0" width="900">' \
                       '{1}</table>' \
                       '</center></body></html>'.format(name, table_info)

        file_html_path = "%s_.html" % file_path
        with open(file_html_path, 'w') as f:
            f.write(gen_html)
        return file_html_path, gen_html

    def close_page(self):
        self.driver.close()

    def start(self):

        for login_time in range(3):
            if self.login() is True:
                break
            else:
                self.close_page()
            if login_time == 2:
                print "login failure"
                return False
        pool = ThreadPool(50)
        pool.map(self.error_message,  set(self.get_log_url()))
        pool.close()
        pool.join()
        self.close_page()
        return True


if __name__ == "__main__":

    now_time = dt.datetime.now().strftime('%Y-%m-%d_%H-%M')
    start_time = (dt.datetime.today() - dt.timedelta(weeks=1)).strftime('%Y-%m-%d')
    end_time = now_time[:10]
    url1 = 'https://4g-rep-portal.wroclaw.nsn-rdnet.net/reports/test-runs/?location=shangha&org=L3_SHA&' \
           'end_ft={0}%2000:00:00,{1}%2023:59:59&result=not%20analyzed&limit=1000&' \
           'columns=no,test_case.test_set,hyperlink_set.name,test_case.test_instance.res_tester,start,end,' \
           'result,env_issue_type'.format(start_time, end_time)

    print url1
    file_path = '/home/log/xbu/et_test/not_analyzed_%s' % now_time

    RP = Search_Test_Record(url1, file_path, by_tester=True)

    try:
        RP.start()
    except Exception, e:
        print Exception, e
        RP.close_page()
    print "get basic info--done!"
    mailfrom = 'Xiangfeng.bu@nokia-sbell.com'
    mailto = ['I_LTE_CP_SHG_ET@internal.nsn.com',
              #'xiangfeng.bu@nokia-sbell.com',
              ]
    # cc = ['xiangfeng.bu@nokia-sbell.com']
    # bcc = ['']
    subject = "Not analyzed cases from %s to %s " % (start_time, end_time)

    attachment_list = []
    if RP.by_tester:
        for tester in RP.tester_set:
            tester_file_path = "%s_%s" % (file_path, tester)
            new_tester_file_path, _ = RP.write_page(tester_file_path, tester)
            attachment_list.append(new_tester_file_path)

    new_file_path, overall_html = RP.write_page(file_path)
    attachment_list.append(new_file_path)

    pic_ciyun = ciyun(file_path, '/home/xbu/git/co_work/ET_testlog/ET.png')
    print "gen CIYUN"
    send_mail(mailfrom=mailfrom, mailto=mailto, subject=subject, body=overall_html, body_type='html',
              att_files_path=attachment_list, pic_path=pic_ciyun)
